<?php if(!defined('PUBLIC_DIR')) die('No Access!');
using('System.Data');

Cnamespace('System.Data');
abstract class Units implements iUnits{
	private static function SI(){
		return array(
			'y' => -10, -10 => array(-24, 'y', 'jokto'),
			'z' => -9, -9 => array(-21, 'z', 'zepto'),
			'a' => -8, -8 => array(-18, 'a', 'atto'),
			'f' => -7, -7 => array(-15, 'f', 'femto'),
			'p' => -6, -6 => array(-12, 'p', 'piko'),
			'n' => -5, -5 => array(-9, 'n', 'nano'),
			'µ' => -4, -4 => array(-6, 'µ', 'mikro'),
			'm' => -3, -3 => array(-3, 'm', 'mili'),
			'c' => -2, -2 => array(-2, 'c', 'centy'),
			'd' => -1, -1 => array(-1, 'd', 'decy'),
			0 => array(0, '', ''),
			'da' => 1, 1 => array(1, 'da', 'deka'),
			'h' => 2, 2 => array(2, 'h', 'hekto'),
			'k' => 3, 3 => array(3, 'k', 'kilo'),
			'M' => 4, 4 => array(6, 'M', 'mega'),
			'G' => 5, 5 => array(9, 'G', 'giga'),
			'T' => 6, 6 => array(12, 'T', 'tera'),
			'P' => 7, 7 => array(15, 'P', 'peta'),
			'E' => 8, 8 => array(18, 'E', 'eksa'),
			'Z' => 9, 9 => array(21, 'Z', 'zetta'),
			'Y' => 10, 10 => array(24, 'Y', 'jotta'),
		);
	}


	public static function Data($count = 0, $Unit = ' b'){
		$UI = array(
			'b' => 0, 0 => array(0, 'b', 'bit'),
			'B' => 1, 1 => array(1, 'B', 'bajt'),
		);
		
		$SI = self::SI();
		$Unit = self::PartUnit($Unit, $SI, $UI);
		$count = (is_numeric($count) ? (float)$count : 0);
		$p = ($Unit['p'] == '' ? 0 : $SI[$Unit['p']]);
		$num = $count * pow(10, -$SI[$p][0]);

		if($count != 0){
			while($count > 1){
				if($SI[$p+1][0] % 3 == 0){
					$count = $num / pow(1024, $SI[$p+1][0]/3);
				} $p++;
			}
			while($count < 1){
				if($SI[$p-1][0] % 3 == 0){
					$count = $num / pow(1024, $SI[$p-1][0]/3);
				} $p--;
			}
		}
		
		return round($count, 2) . " " . $SI[$p][1] . $Unit['s'];
	}
	
	public static function PartUnit($Unit, $SI = null){
		if(!is_array($SI)) $SI = self::SI();
		$p = '';
		$s = $Unit;
		if(strlen($Unit) > 1){
			$p = substr($Unit, 0, 2);
			if(array_key_exists($p, $SI))
				$s = substr($Unit, 2);
			else{
				$p = substr($Unit, 0, 1);
				if(array_key_exists($p, $SI))
					$s = substr($Unit, 1);
				else
					$p = '';
			}
		}
		return array('p' => $p, 's' => $s);
	}
}